<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/25
 * Time: 15:06
 */

namespace App\OpenApi\AdminApi\Admin;

use App\Service\Core\Admin\Menu\AdminMenuService;
use App\Service\Core\Admin\Power\AdminUserPowerService;
use App\Service\Core\Admin\Power\AdminUserPowerStoreItemService;
use App\Service\Core\Admin\Power\AdminUserPowerStoreService;
use App\Service\Core\Admin\Role\AdminUserRoleService;
use App\Service\OpenApi\AdminApi\OpenBaseApi;
use App\Service\ParamsService;

class AdminUserPowerApi extends OpenBaseApi
{
    public function index(): array
    {
        $role_id = $this->input('role_id');
        if (empty($role_id)) {
            return alert_info(1, '角色ID未传递');
        }
        $menu_tree = AdminMenuService::getMenuTreeList();
        $role_info = AdminUserRoleService::getInstance()->getOne($role_id);
        $power_list = AdminUserPowerService::getInstance()->getTypeList($role_id);
        $role_data_type = [];
        foreach (ParamsService::$admin_user_role_data_type as $key => $label) {
            $role_data_type[] = ['value' => $key, 'label' => $label];
        }
        return alert_info(0, 'ok', [
            'menu_tree' => $menu_tree,
            'role_info' => $role_info,
            'role_data_type' => $role_data_type,
            'menu_checked' => $power_list[ParamsService::ADMIN_USER_POWER_TYPE_MENU] ?? [],
        ]);
    }

    /**
     * @return array
     * @throws \Throwable
     */
    public function store(): array
    {
        $menu_power = $this->input('menu_power');
        $item = (new AdminUserPowerStoreItemService());
        foreach ($menu_power as $menu) {
            $item->link_id = $menu['id'];
            $item->link_type = ParamsService::ADMIN_USER_POWER_TYPE_MENU;
            $item->store();
        }
        return (new AdminUserPowerStoreService())
            ->setRoleId($this->input('role_id'))
            ->setPermissions($this->input('permissions'))
            ->setPowerData($item)
            ->setOperate($this->operate_id, $this->operate_by)
            ->store();
    }
}
